package com.example.mybatislearn.common.mapper.mapping;

import com.example.mybatislearn.common.mapper.converter.customer.SmartTypeConverter;

import java.util.ArrayList;
import java.util.List;

public class SmartBeanMapping<S, D>  {
    private Class<S> srcType;

    private Class<D> destType;

    private List<SmartFieldMapping> fieldMappingList = new ArrayList<>();

    private SmartBeanMapping(Class<S> srcType, Class<D> destType) {
        this.srcType = srcType;
        this.destType =  destType;
    }

    public static <S, D> SmartBeanMapping<S, D> create(Class<S> srcType, Class<D> destType) {
        return new SmartBeanMapping(srcType, destType);
    }

    public SmartBeanMapping fields(String srcFieldName, String destFieldName) {
        fields(srcFieldName, destFieldName, null);

        return this;
    }

    public SmartBeanMapping fields(String srcFieldName, SmartTypeConverter typeConverter) {
        fields(srcFieldName, null, typeConverter);

        return this;
    }

    public SmartBeanMapping fields(String srcFieldName, String destFieldName, SmartTypeConverter typeConverter) {
        SmartFieldMapping fieldMapping = SmartFieldMapping.create(srcFieldName, destFieldName, typeConverter);
        fieldMappingList.add(fieldMapping);

        return this;
    }

    public List<SmartFieldMapping> getFieldMappings() {
        return fieldMappingList;
    }

    public List<SmartFieldMapping> getFieldMappings(String srcFieldName) {
        List<SmartFieldMapping> srcFieldMappingList = new ArrayList<>();
        for (SmartFieldMapping each : fieldMappingList) {
            if (each.getSrcFieldName().equals(srcFieldName)) {
                srcFieldMappingList.add(each);
            }
        }

        return srcFieldMappingList;
    }

    public SmartFieldMapping getFieldMapping(String srcFieldName) {
        List<SmartFieldMapping> fieldMappingList = getFieldMappings(srcFieldName);
        if (fieldMappingList != null && fieldMappingList.size() > 0) {
            return fieldMappingList.get(0);
        }
        return null;
    }

    public Class<S> getSrcType() {
        return srcType;
    }

    public Class<D> getDestType() {
        return destType;
    }
}
